package task

import (
	"fmt"
	"os"
	"os/exec"

	"github.com/robfig/cron"
)

// Task 任务
type Task struct {
	ID     int
	Status int // 状态 0 停止 1 启动
	Spec   string
	Job    string
	Name   string
}

// Tasks 任务队列
type Tasks struct {
	task    map[int]*Task
	running bool
	done    chan struct{}
}

// NewTasks 初始化任务队列
func NewTasks() *Tasks {
	return &Tasks{
		task:    make(map[int]*Task, 10),
		running: false,
		done:    make(chan struct{}),
	}
}

// Add 添加一个任务到队列中
func (t *Tasks) Add(id int, name, spec, job string) {
	task := &Task{
		ID:     id,
		Status: 1,
		Spec:   spec,
		Job:    job,
		Name:   name,
	}
	t.task[id] = task
}

// 返回当前运行的任务队列

// Run 执行任务队列中可启动的任务
func (t *Tasks) Run() {
	if t.running {
		return
	}
	t.running = true

	c := cron.New()
	for _, v := range t.task {
		if v.Status == 0 {
			continue
		}
		spec := v.Spec
		job := v.Job
		c.AddFunc(spec, func() {
			//			fmt.Println(job)
			cmd := exec.Command("sh", "-c", job)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			err := cmd.Run()
			if err != nil {
				fmt.Println(err)
			}
		})
	}
	c.Start()

	select {
	case <-t.done:
		c.Stop()
		c = nil
		t.task = make(map[int]*Task)
		fmt.Println("===任务暂停===")
		return
	}
}

// Stop 任务暂停
func (t *Tasks) Stop() {
	if !t.running {
		return
	}
	t.done <- struct{}{}
	t.running = false
}
